package com.xuan.contest.service.impl;

import com.xuan.contest.common.cache.CacheFactory;
import com.xuan.contest.common.job.CheckAnswerJob;
import com.xuan.contest.common.job.ExecuteJob;
import com.xuan.contest.common.utils.SpringContextHolder;
import com.xuan.contest.dao.ContestMapper;
import com.xuan.contest.entry.ContestEntity;
import com.xuan.contest.entry.ProblemEntity;
import com.xuan.contest.entry.UserAnswerEntity;
import com.xuan.contest.entry.WinnerListEntity;
import com.xuan.contest.service.IBussinessService;
import com.xuan.contest.service.IProblemService;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author XinZhaoXuan
 * @date 2018/9/30
 */
@Component
public class BussinessServiceImpl implements IBussinessService {

    Logger logger = LoggerFactory.getLogger(ContestServiceImpl.class);

    private int WINNER_SIZE = 2000;

    volatile int winnerNumber = 1;

    @Autowired
    private IProblemService problemService;

    @Autowired
    private ContestMapper contestMapper;

    /**
     * 执行 处理答题 job
     */
    @Override
    public void workAnswerJob() {
        logger.info("定时任务 开始 执行");
        List<UserAnswerEntity> list = CacheFactory.redisCache().
                getCacheQueue(CacheFactory.QUEUE_ANSWER, UserAnswerEntity.class);

        System.out.println("size ======" + list.size());

        ProblemEntity problemEntity = new ProblemEntity();

        Integer contestId = CacheFactory.redisCache().getCacheObject(CacheFactory.CONTEST_RUNNING);
        if (contestId != null) {
            ContestEntity contestEntity = contestMapper.selectById(contestId);
            WINNER_SIZE = contestEntity.getWinnerNumber();
        }

        Integer answer;
        WinnerListEntity winnerListEntity;
        for (UserAnswerEntity entity : list) {
            answer = problemService.selectAnswerByQuestion(entity.getProblemId());

            if (entity.getAnswer().compareTo(answer) == 0 && winnerNumber < WINNER_SIZE) {
                winnerListEntity = new WinnerListEntity(entity.getUserId(), entity.getContestId(), entity.getProblemId());
                winnerListEntity.insert();
            }

            entity.insert();

            winnerNumber++;
        }

        logger.info("定时任务 删除 执行");
        ExecuteJob schedulerAllJob = SpringContextHolder.getBean("executeJob");
        try {
            schedulerAllJob.stopJob(CheckAnswerJob.class);
        } catch (SchedulerException e) {
            logger.error("抢答题 定时任务 结束失败");
            e.printStackTrace();
        }
    }
}
